<template>
    <div class="box">
        <!-- 上面 -->
        <div class="top-box">
            <div class="top">
                <div style="width:200px" class="top-body">内卷队-喵了个喵</div>
                <div v-if="!yc">
                    <div class="top-body">剩余：{{ allCardList.length }}个</div>
                    <div class="top-body">用时：{{ formattedTime }}</div>
                    <div class="top-body">总分：{{ totalScore }}</div>
                </div>
            </div>
            <br />
            <!-- 遮罩图层 -->
            <div v-if="yc" class="card-box" style="display: flex;align-items: center;justify-content: center;">
                <el-button @click="jiandan" type="success" plain>简单</el-button>
                <el-button @click="yiban" type="warning" plain>一般</el-button>
                <el-button @click="kunnan" type="danger" plain>困难</el-button>
                <el-button @click="startTimer" type="primary">开始游戏</el-button>
            </div>
            <!-- 上面的方块盒子 -->
            <div v-else class="card-box">
                <div class="card" @click="selectedCard(item, index, $event)" v-for="(item, index) in allCardList"
                    :key="index" :style="{ left: item.left, top: item.top }">
                    <img class="img" :src="'/assets/' + item.icon" />
                </div>
            </div>
            <p></p>
            <!-- 下面的方块盒子 -->
            <div class="selected-card-box">
                <div class="selected-card" v-for="(item, index) in selectedCardList" :key="index">
                    <img class="img" :src="'/assets/' + item.icon" />
                </div>
            </div>
            <!-- 按钮盒子 -->
            <div class="btn" v-if="!yc">
                <!-- <el-button @click="initData()" type="primary">重新开始</el-button> -->
                <el-button @click="fanhui" type="primary">重新关卡</el-button>
                <el-button @click="backCard()" type="primary">撤回</el-button>
            </div>
        </div>


    </div>
</template>

<script setup>
import { ref, watch, } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'



const timer = ref(0);
const isRunning = ref(false);
const yc = ref(true);


// 定义选择关卡难度以及卡片数量
let shuzi = ref(48);
let nandu = ref(0);
const jiandan = () => {
    // shuzi.value = 3;
    shuzi.value = 48;
    nandu = 1;
    // console.log(shuzi);
    startTime()
}
const yiban = () => {
    shuzi.value = 84;
    nandu = 2;
    startTime()
}
const kunnan = () => {
    shuzi.value = 303;
    nandu = 3;
    startTime()
}


// 格式化计时器的时间
const formattedTime = ref('00:00:00');
const formatTime = () => {
    const hours = Math.floor(timer.value / 3600);
    const minutes = Math.floor((timer.value % 3600) / 60);
    const seconds = timer.value % 60;
    formattedTime.value = `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
};

let intervalId = ref(0);
// 游戏开始后的计时器
const startTimer = () => {
    initData()
    // console.log(yc);
    isRunning.value = true;
    yc.value = false;

    intervalId = setInterval(() => {
        timer.value++;
        formatTime();
    }, 1000);

};

// 补零函数
const padZero = (num) => {
    return num.toString().padStart(2, '0');
};

const positionList = ref([]);
const allCardList = ref([]);
const selectedCardList = ref([]);
const currentSelectedCard = ref({});
const selectHistory = ref([]);
const iconList = [
    { picIndex: 0, icon: '1.png' },
    { picIndex: 1, icon: '2.png' },
    { picIndex: 2, icon: '3.png' },
    { picIndex: 3, icon: '4.png' },
    { picIndex: 4, icon: '5.png' },
    { picIndex: 5, icon: '6.png' },
    { picIndex: 6, icon: '7.png' },
    { picIndex: 7, icon: '8.png' },
    { picIndex: 8, icon: '9.png' },
    { picIndex: 9, icon: '10.png' },
    { picIndex: 10, icon: '11.png' }
];
const totalScore = ref(0);


// 重新开始按钮，刷新页面
const fanhui = () => {
    location.reload();
}


// 按钮
const backCard = () => {
    // console.log(allCardList.value);
    // console.log(selectHistory.value);
    if (selectHistory.value.length > 0) {
        const backItem = selectHistory.value[selectHistory.value.length - 1];
        allCardList.value.push(backItem);
        allCardList.value.sort((a, b) => {
            return a.id - b.id;
        });
        selectHistory.value = selectHistory.value.filter((item) => {
            return item.id !== backItem.id;
        });
        selectedCardList.value = selectedCardList.value.filter((item) => {
            return item.id !== backItem.id;
        });
    } else {
        alert('没有可以撤回的卡片了！');
    }
};

// 获取提交的时间
function startTime() {
    let today = new Date();
    //日期格式化
    let yyyy = today.getFullYear(); // 获取年
    let MM = String(today.getMonth() + 1).padStart(2, '0'); //获取月份，1 月为 0，给小于10的数字前加0
    let DD = String(today.getDate()).padStart(2, '0'); // 获取日
    let h = today.getHours();//获取时
    let m = String(today.getMinutes()).padStart(2, '0');//获取分
    let s = String(today.getSeconds()).padStart(2, '0');//获取秒
    // let time = "当前时间：" + yyyy + '年' + MM + '月' + DD + '日' + h + ":" + m + ":" + s;
    let end_time = yyyy + '-' + MM + '-' + DD + " " + h + ":" + m + ":" + s;
    //定时器，每秒更新时间
    let t = setTimeout(function () { startTime() }, 500);
    return end_time
}

// 选择卡片进行判断
const selectedCard = (item, index, event) => {
    // console.log(item, index, event.srcElement);
    const isHover = hasOverLayer(event.srcElement);
    // console.log(isHover);
    if (!isHover) {
        currentSelectedCard.value = item;
        allCardList.value.splice(index, 1);
        selectedCardList.value.push(item);
        selectHistory.value.push(item);
        selectedCardList.value.sort((a, b) => {
            return a.picIndex - b.picIndex;
        });
        setTimeout(() => {
            // 判断是否可以消除
            checkRemove();
            if (allCardList.value.length === 0) {
                ElMessageBox.prompt(
                    '本关消除方块数量：' + shuzi.value + ' 用时：' + formattedTime.value + ' 得分：' + totalScore.value + '  请在下方输入用户名',
                    '挑战成功',
                    {
                        confirmButtonText: '确定',
                        type: 'success',
                        center: true,
                        inputPattern: /^[\u4e00-\u9fa5]{1,7}$|^[\dA-Za-z_]{1,14}$/,
                        inputErrorMessage: "用户名不能为空,且最长不得超过7个汉字,或14个字节(数字、字母和下划线)"
                    })
                    .then(({ value }) => {
                        ElMessage({
                            type: 'success',
                            message: '数据存储成功',
                        })
                        let dangqianshijian = startTime()
                        const game = {
                            username: value,
                            totalScore: totalScore.value,
                            time: timer.value,
                            numbers: shuzi.value,
                            difficulty_factor: nandu,
                            end_time: dangqianshijian
                        }
                        console.log(game);
                        stopTimer();
                        // 发送获取数据的请求
                        fetch('/api/add', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify(game)
                        }).then(function (data) {
                            // data.json().then(function (result) {

                            // })
                            console.log(data);
                        })

                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消了',
                        })
                    })
            }
            if (selectedCardList.value.length >= 7) {
                stopTimer()
                ElMessageBox.confirm(
                    '本关消除方块数量：' + shuzi.value + ' 用时：' + formattedTime.value + ' 得分：' + totalScore.value,
                    '挑战失败',
                    {
                        confirmButtonText: '重新开始',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true,
                    })
                    .then(() => {
                        ElMessage({
                            type: 'primary',
                            message: '重新开始',
                        })
                        // stopTimer();
                        startTimer();
                        // initData();
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消',
                        })
                        location.reload();
                    })

            }
        }, 200);
    }
};

// 判断是否可以消除
const checkRemove = () => {
    let num = 0;
    selectedCardList.value.forEach((item) => {
        if (currentSelectedCard.value.icon === item.icon) {
            num++;
        }
    });
    if (num === 3) {
        selectedCardList.value = selectedCardList.value.filter((item) => {
            return item.icon !== currentSelectedCard.value.icon;
        });
        selectHistory.value = selectHistory.value.filter((item) => {
            return item.icon !== currentSelectedCard.value.icon;
        });
        totalScore.value++; // 消除三个一样的得一分
        if (allCardList.value.length === 0) {
            // 最后一组内容消除完，显示弹出框
            // showDialog.value = true;
            stopTimer();
        }
    }
};

// 停止计时器
const stopTimer = () => {
    // console.log("停止计时");
    clearInterval(intervalId);
    isRunning.value = false;
};

// 监测元素是否被覆盖
const hasOverLayer = (element) => {
    const document = element.ownerDocument;
    const rect = element.getBoundingClientRect(); // 获取目标的矩形信息
    let x = rect.x;
    let y = rect.y;
    let width = rect.width;
    let height = rect.height;
    x |= 0;
    y |= 0;
    width |= 0;
    height |= 0;
    // 四顶点取样
    const elements = [
        document.elementFromPoint(x + 1, y + 1),
        document.elementFromPoint(x + width - 1, y + 1),
        document.elementFromPoint(x + 1, y + height - 1),
        document.elementFromPoint(x + width - 1, y + height - 1),
    ];
    // 判断非本身及非子孙元素
    return elements.filter((el) => el !== null).some((el) => el !== element && !element.contains(el));
};


// 生成随机图标
const createIcon = () => {
    // console.log(shuzi.value);
    let index = 0;
    allCardList.value = [];
    let random = 0;
    // console.log(random);
    // 303  51
    for (let i = 0; i < shuzi.value; i++) {
        if (i % 3 === 0) {
            random = Math.floor(Math.random() * 11);
        }
        allCardList.value.push({
            id: index++,
            icon: iconList[random].icon,
            picIndex: iconList[random].picIndex,
        });
        console.log(allCardList.value.length);
        // console.log(iconList[random].icon);
    }
    allCardList.value.sort(() => {
        return Math.random() > 0.5 ? 1 : -1;
    });
    allCardList.value.forEach((item, index) => {
        item.id = index;
    });


    // 循环堆叠
    let pos = 0;
    allCardList.value.forEach((item) => {
        item['left'] = positionList.value[pos].left;
        item['top'] = positionList.value[pos].top;
        pos++;
        if (pos > 84) {
            pos = 0;
        }
    });

    // console.log(allCardList.value);
};

// 初始化数据
const initData = () => {
    formattedTime.value = '00:00:00';
    positionList.value = [];
    allCardList.value = [];
    selectedCardList.value = [];
    currentSelectedCard.value = {};
    totalScore.value = 0
    timer.value = 0
    let index = 0;
    // 第一层
    let left = 0;
    let top = 0;
    for (let i = 0; i < 7; i++) {
        for (let j = 0; j < 7; j++) {
            positionList.value.push({ id: index++, picIndex: 1, left: left + 'px', top: top + 'px' });
            left += 50;
        }
        left = 0;
        top += 50;
    }

    // 第二层
    left = 25;
    top = 25;
    for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 6; j++) {
            positionList.value.push({ id: index++, picIndex: 1, left: left + 'px', top: top + 'px' });
            left += 50;
        }
        left = 25;
        top += 50;
    }

    // 生成随机图标
    createIcon();
};



</script>

<style scoped  lang="scss">
.img {
    width: 30px;
    height: 30px;
}

.top {
    width: 50%;
    margin: 0 auto;
    left: 45%;
    top: 0px;

    .top-body {
        padding-top: 20px;
        margin: 0 auto;
        width: 200px;
        display: flex;
        justify-content: center;
        color: #d1f617;
        font-size: 24px;
        font-weight: bolder;
    }
}

.top-box {
    width: 100%;
    height: 790px;
    /* background-color: antiquewhite; */
    background: url('../assets/bj.jpg') no-repeat;
    background-position: center;
    background-size: cover;
}

.card-box {
    width: 350px;
    height: 44%;
    background-color: #dddaaa;
    opacity: 0.9;
    margin: 0 auto;
    position: relative;


}

.card {
    width: 44px;
    height: 44px;
    line-height: 48px;
    font-size: 36px;
    border: 1px solid #666;
    text-align: center;
    position: absolute;
    box-shadow: 0px 0px 6px 0px #545454;
    background-color: #fff;
}

.selected-card-box {
    width: 350px;
    height: 50px;
    background-color: rgb(253, 217, 170);
    margin: 0 auto;
}

.selected-card {
    width: 48px;
    height: 48px;
    line-height: 48px;
    font-size: 36px;
    border: 1px solid #666;
    text-align: center;
    background-color: #fff;
    display: inline-block;
}

.btn {
    margin: 0 auto;
    width: 350px;
    text-align: center;
    margin-top: 24px;
}

.el-icon-s-.png {
    color: #aa0000;
}

.el-icon-platform-eleme {
    color: #005500;
}

.el-icon-delete-solid {
    color: #aa5500;
}

.el-icon-s-tools {
    color: #aaaa00;
}

.el-icon-user-solid {
    color: #000000;
}

.el-icon-warning {
    color: #316394;
}

.el-icon-picture {
    color: #00007f;
}

.el-icon-upload {
    color: #760000;
}

.el-icon-message-solid {
    color: #9a004d;
}

.el-icon-video-camera-solid {
    color: #ffaa7f;
}

.el-icon-s-platform {
    color: #848441;
}
</style>
  